from bs4 import BeautifulSoup, NavigableString

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

def tag_base_test():
    # soup, tag 基本用法展示
    soup = BeautifulSoup(html_doc, 'lxml')
    # soup = BeautifulSoup(html_doc, 'html.parser')
    # print(soup.prettify())
    print("soup.title:", soup.title)                 # title tag
    print("soup.title.name:", soup.title.name)
    print("soup.title.string:", soup.title.string)

    print("soup.title.parent:", soup.title.parent)
    print("-"*20)
    print("soup.p:", soup.p)                        # p tag
    print("soup.p.string:", soup.p.string)          # NavigableString
    if soup.p.has_attr('class'):                    # has_attr
        print("soup.p['class']:", soup.p['class'])  # attr  or use get('class')

    print("soup.a:", soup.a)
    print("soup.find_all('a'):", soup.find_all('a'))
    print('soup.find(id="link3"):', soup.find(id="link3"))

    print("\n从文档中找到所有<a>标签的链接:---")
    for link in soup.find_all('a'):
        print(link.get('href'))             # get attrs
    print("\n从文档中获取所有文字内容:---")
    print(soup.get_text())                  # get text


def find_test():
    soup = BeautifulSoup(html_doc, 'lxml')

    def has_class_but_no_id(tag):
        return tag.has_attr('class') and not tag.has_attr('id')

    tags = soup.find_all(has_class_but_no_id)
    for tag in tags:
        print(tag)

    def surrounded_by_strings(tag):
        return (isinstance(tag.next_element, NavigableString)
                and isinstance(tag.previous_element, NavigableString))

    for tag in soup.find_all(surrounded_by_strings):
        print(tag.name)


def select_test():
    pass

if __name__ == '__main__':
    # tag_base_test()
    find_test()

